<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['friends'])&&isset($_POST['user_id'])) {
    $friends = $_POST['friends'];
     $user_id = $_POST['user_id'];
   $myArray = json_decode($friends, true);
   //delete friend

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();
    //update game
    if(isset($_POST['game']))
    {
            $game = $_POST['game'];
           $mArray = json_decode($game, true);
        mysql_query("DELETE FROM game WHERE user_id = '$user_id'");
         foreach ($mArray as $key => $value) {
        mysql_query("INSERT INTO game(user_id, id_level,score,rate) VALUES('$user_id', '$value[0]', '$value[1]', '$value[2]')");

            //echo $value[0];
         /*foreach ($value as $k => $v) { 
                 echo "$v $k <br />"; 
            }*/
                }
    }
	mysql_query("DELETE FROM friends WHERE uid = '$user_id'");

    foreach ($myArray as $key => $value) {
	
        // mysql inserting a new row
        $result = mysql_query("INSERT INTO friends(uid, uid_friend) VALUES('$user_id', '$value')");
                    }
                      // mysql inserting a new row
        $result = mysql_query("INSERT INTO friends(uid, uid_friend) VALUES('$user_id', '$user_id')");
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["responseCode"] = 1;
        $response["responseMessage"] = "friends successfully insert.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["responseCode"] = -1;
        $response["responseMessage"] = "Oops! An error occurred.";
        
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["responseCode"] = -1;
    $response["responseMessage"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>